package com.platform.api;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.platform.entity.UserEntity;
import com.platform.service.MpMsgService;
import com.platform.service.TokenService;
import com.platform.service.UserService;
import com.platform.toutiao.api.TouTiaoServiceHttpClient;
import com.platform.toutiao.bean.TouTiaoCode2SessionResult;
import com.platform.toutiao.bean.TouTiaoUserInfo;
import com.platform.toutiao.config.TouTiaoConfiguration;
import com.platform.toutiao.error.TouTiaoErrorException;
import com.platform.util.ApiBaseAction;
import com.platform.utils.MapUtils;
import com.platform.utils.R;
import com.platform.utils.RequestUtil;

import me.chanjar.weixin.common.error.WxErrorException;

@Controller
@RequestMapping("/ttlogin")
public class ApiTouTiaoLoginController extends ApiBaseAction {
	private Logger logger = Logger.getLogger(getClass());
	@Autowired
	private UserService userService;
	@Autowired
	private TokenService tokenService;
	@Autowired
	private MpMsgService mpMsgService;
	@Autowired
	private TouTiaoConfiguration touTiaoConfiguration;

///////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////小程序  					///////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////
	@ResponseBody
	@RequestMapping(value = "/ttsilentcheck/{mpId}")
	public R silentCheck(@PathVariable("mpId") Integer mpId, HttpServletRequest request,
			HttpServletResponse response) {
		String code = request.getParameter("code");
		String ip = RequestUtil.getIpAddrByRequest(request);
		Integer referenceId = null;
		if (request.getParameter("referenceId") != null) {
			try {
				referenceId = Integer.valueOf(request.getParameter("referenceId"));
			} catch (NumberFormatException e) {
				referenceId = 0;
			}
		}
		UserEntity user = null;
		TouTiaoServiceHttpClient ttService = touTiaoConfiguration.getTtService(mpId);
		try {
			TouTiaoCode2SessionResult ttSessionResult = ttService.code2Session(code);
			user = userService.loginByTtXcx(ttSessionResult, mpId, ip, referenceId);
		} catch (TouTiaoErrorException e) {
			logger.error(e.getMessage(), e);
			return R.error(e.getMessage());
		}

		Map<String, Object> tokenMap = tokenService.createToken(user.getId());
		String token = MapUtils.getString("token", tokenMap);
		return R.ok().put("user", user).put("token", token).put("expireTime", tokenMap.get("expireTime"));
	}

	@ResponseBody
	@RequestMapping(value = "/ttcheck/{mpId}")
	public R xcxCheck(@PathVariable("mpId") Integer mpId, HttpServletRequest request, HttpServletResponse response) {
		String code = request.getParameter("code");
		Integer referenceId = null;
		if (request.getParameter("referenceId") != null) {
			try {
				referenceId = Integer.valueOf(request.getParameter("referenceId"));
			} catch (NumberFormatException e) {
				referenceId = 0;
			}
		}
		String signature = request.getParameter("signature");
		String encryptedData = request.getParameter("encryptedData");
		String iv = request.getParameter("iv");
		String ip = RequestUtil.getIpAddrByRequest(request);
		UserEntity user = null;
		TouTiaoServiceHttpClient ttService = touTiaoConfiguration.getTtService(mpId);
		try {
			TouTiaoCode2SessionResult ttSessionResult = ttService.code2Session(code);
			TouTiaoUserInfo ttUser = ttService.getUserInfo( encryptedData,ttSessionResult.getSessionKey(), iv);
			user = userService.loginByTtXcx(ttUser, mpId, ip, referenceId);
		} catch (TouTiaoErrorException e) {
			logger.error(e.getMessage(), e);
			return R.error(e.getMessage());
		}

		Map<String, Object> tokenMap = tokenService.createToken(user.getId());
		String token = MapUtils.getString("token", tokenMap);
		return R.ok().put("user", user).put("token", token).put("expireTime", tokenMap.get("expireTime"));
	}
}
